package com.bionet.metaboservice.controller;

/**
 * @author hzx
 * @create 2021-09-18 16:41
 */

import cn.dev33.satoken.sso.SaSsoUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 前后台分离架构下集成SSO所需的代码
 */
@RestController
@RequestMapping("/metaboservice/client")
public class H5Controller {

    // 当前是否登录
    @PostMapping("/isLogin")
    public Object isLogin() {
        System.out.println(StpUtil.isLogin());return SaResult.data(StpUtil.isLogin());
    }

    // 返回SSO认证中心登录地址
    @PostMapping("/getSsoAuthUrl")
    public SaResult getSsoAuthUrl(String clientLoginUrl) {
        String serverAuthUrl = SaSsoUtil.buildServerAuthUrl(clientLoginUrl, "");
        return SaResult.data(serverAuthUrl);
    }

    // 根据ticket进行登录
    @PostMapping("/doLoginByTicket")
    public SaResult doLoginByTicket(String ticket) {
        Object loginId = checkTicket(ticket);
        if(loginId != null) {
            StpUtil.login(loginId);
            return SaResult.data(StpUtil.getTokenValue());
        }
        return SaResult.error("无效ticket：" + ticket);
    }

    @GetMapping("/logout")
    public void doLogOut(HttpServletRequest request, HttpServletResponse response) throws IOException {
        StpUtil.logout();
        String back = response.encodeRedirectURL(request.getParameter("back"));
        response.sendRedirect(back);
    }

    // 校验 Ticket码，获取账号Id
    private Object checkTicket(String ticket) {
        return SaSsoUtil.checkTicket(ticket);
    }

    // 全局异常拦截
    @ExceptionHandler
    public SaResult handlerException(Exception e) {
        e.printStackTrace();
        return SaResult.error(e.getMessage());
    }

}

